// 接口请求
import Axios from 'axios';
import { getToken } from '@/utils/cookie.js';

const { VITE_INTERFACE_DOMAIN } = import.meta.env;

const axios = Axios.create({
  baseURL: VITE_INTERFACE_DOMAIN,
  timeout: 0,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

axios.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

axios.interceptors.response.use(
  (response) => {
    const { data } = response;
    console.log(data);
    return Promise.resolve(data);
  },
  (error) => {
    return Promise.reject(error);
  },
);

const getRequest = (requestConfig) => {
  return (url, data, config = { baseURL: VITE_INTERFACE_DOMAIN }) => {
    const requestFunConfig =
      typeof requestConfig === 'string' ? { method: requestConfig } : requestConfig;
    const { method } = requestFunConfig;
    const { baseURL, customConfig, ...axiosConfig } = config;
    return axios(url, {
      baseURL,
      method,
      [method === 'get' ? 'params' : 'data']: data,
      customConfig,
      ...requestFunConfig,
      ...axiosConfig,
    });
  };
};
export const Post = getRequest('post');
export const Get = getRequest('get');
